package com.opesoft.pf.hibernate;

import java.util.ArrayList;
import java.util.List;

import com.opesoft.fw.core.utils.SQLUtils;

public class SimpleHQL
{
	String pojo; // 要操作的Pojo
	String alias="a"; // 别名
	String[] orderBy; // Order by子句
	List<Condition> conditions=new ArrayList<Condition>(); // 条件子句中的条件

	public SimpleHQL(String pojo)
	{
		this.pojo=pojo;
	}

	public void addStringCondition(String field,String op,String value)
	{
		if(!SQLUtils.isNull(value)) this.conditions.add(new Condition(field,op,value,Condition.STRING_TYPE));
	}

	public void addNumCondition(String field,String op,String value)
	{
		if(!SQLUtils.isNull(value)) this.conditions.add(new Condition(field,op,value,Condition.NUM_TYPE));
	}

	public void addStringLikeCondition(String field,String value)
	{
		if(!SQLUtils.isNull(value)) this.conditions.add(new Condition(field,"like","%"+value+"%",Condition.STRING_TYPE));
	}

	public String hql()
	{
		String hql="from "+this.pojo+" "+this.alias;

		if(this.conditions.size()>0)
		{
			hql+=" where";
			for(int i=0;i<this.conditions.size();i++)
			{
				Condition cond=this.conditions.get(i);
				hql+=" "+cond.hql(this.alias);
				if(i<(this.conditions.size()-1)) hql+=" and";
			}
		}

		if(this.orderBy!=null&&this.orderBy.length>0)
		{
			hql+=" order by ";
			for(int i=0;i<this.orderBy.length;i++)
			{
				String field=this.orderBy[i];
				hql+=this.alias+"."+field;
				if(i<(this.orderBy.length-1)) hql+=" , ";
			}
		}

		return hql;
	}

	public String toString()
	{
		return this.hql();
		
	}
	
	public String getAlias()
	{
		return alias;
	}

	public void setAlias(String alias)
	{
		this.alias=alias;
	}

	public String[] getOrderBy()
	{
		return orderBy;
	}

	public void setOrderBy(String[] orderBy)
	{
		this.orderBy=orderBy;
	}
}

class Condition
{
	String field; // 字段名
	String op; // 操作符
	String value; // 值
	int type; // 值的类型
	static int STRING_TYPE=1; // 字符串类型
	static int NUM_TYPE=2; // 数字类型

	public Condition(String field,String op,String value,int type)
	{
		this.field=field;
		this.op=op;
		this.value=value;
		this.type=type;
	}

	public String hql()
	{
		String hql=this.field+" "+this.op;
		if(this.type==Condition.STRING_TYPE) hql+=" '"+this.value+"'";
		else hql+=" "+this.value;
		return hql;
	}

	public String hql(String alias)
	{
		return alias+"."+this.hql();
	}

}